package edu.mtu.citizenscience.ethnography;

import java.io.IOException;

import edu.mtu.citizenscience.ethnography.database.Interview;
import edu.mtu.citizenscience.ethnography.util.DataServiceActivity;
import edu.mtu.citizenscience.ethnography.util.Util;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;


/**
 * Creates a new Interview upon pressing any of the buttons within,
 * and then passes this new interview id to the method the button starts.
 * The id is passed through extras in the intent, under the key "interviewID"
 * If that key returns null, there wasn't an interview passed, and the activity 
 * operates under the assumption that it must create a new interview. 
 * @author john
 *
 */
public class NewInterviewActivity extends DataServiceActivity {

	// Class constants
	private static final int NO_INTERVIEW = -1;

	// Global activity variables
	private Interview currentinterview = null;
	private int currentInterviewID;
	private boolean shouldSaveOnStop;

	//Boilerplate log tag
	private static final String LOG_TAG = "NewInterviewActivity";

	// Buttons
	private Button beginRecordingButton;
	private Button interviewDataButton;

	/**
	 * Loads the layout on activity creation.
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(LOG_TAG, LOG_TAG + " is being created");
		setContentView(R.layout.activity_new_interview);

		beginRecordingButton = (Button) findViewById(R.id.start_recording);
		interviewDataButton = (Button) findViewById(R.id.set_interview_data);
		
		if (savedInstanceState == null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				currentInterviewID = extras.getInt(Util.ID_KEY, NO_INTERVIEW);
			} else {
				currentInterviewID = NO_INTERVIEW;
			}
		} else {
			currentInterviewID = savedInstanceState.getInt(Util.ID_KEY);
		}
	}


	/**
	 * If another activity passed the current interview ID back to this activity,
	 * put it to use to keep from possibly creating another interview to replace it.
	 * Cannot create a new interview here due to the database connection not being
	 * resolved until after the function completes.
	 */
	@Override
	protected void onStart(){
		Log.d(LOG_TAG, LOG_TAG + " is being started");
		
		// Disable the buttons until finished initializing
		beginRecordingButton.setEnabled(false);
		interviewDataButton.setEnabled(false);
		
		// Assume we're saving when we're done, until we say we aren't
		shouldSaveOnStop = true;

		// Start running the location system
		//startService(new Intent(getApplicationContext(), CSGpsService.class).putExtra(CSGpsService.UPDATE_RATE, CSGpsService.LOOSE));
		
		super.onStart();
	}

	@Override
	protected void performDatabaseOperation() {
		// Check if creating a new interview or getting an old one
		if (currentInterviewID == NO_INTERVIEW){

			//if the current interview doesn't exist, create one
			try {
				currentinterview = getService().newInterview();
			} catch (IOException e) {
				fail(R.string.io_error);
			}

			// set the id to be put in the intent
			currentInterviewID = currentinterview.getID();
		}
		else {

			// a current interview exists, get the id to put in the intent
			currentinterview = getService().getInterview(currentInterviewID);
			if (currentinterview == null) {
				fail(R.string.activity_start_error);
			}
		}
		beginRecordingButton.setEnabled(true);
		interviewDataButton.setEnabled(true);
	}

	@Override
	protected void onResume(){
		Log.d(LOG_TAG, LOG_TAG + " is resuming");
		super.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(Util.ID_KEY, currentInterviewID);
	}

	/**
	 * When the user returns to the main menu with onBackPressed,
	 * save the interview.
	 */
	@Override
	protected void onStop() {
		if(currentinterview != null && shouldSaveOnStop)
			try {
				getService().saveInterview(currentinterview);
			} catch (IOException e) {
				fail(R.string.io_error);
				e.printStackTrace();
			}
		super.onStop();
	}

	/**
	 * Make sure to close the open interview, then disconnect from the database
	 * on destruction.
	 */
	@Override
	protected void onDestroy() {
		Log.d(LOG_TAG, LOG_TAG + " is being destroyed");
		
		super.onDestroy();
	}


	/**
	 * Callback method for the interview start button.
	 * Creates a new interview if none exists and passes the
	 * interview id to the RecordInterviewActivity.
	 * This activity will let the user get audio recordings
	 * and pictures, which make up the main part of the interview.
	 * @param v parameter required by onButtonPressed
	 */
	public void recordInterview(View v) {
		//Create the intent to switch to the recording activity
		Intent myintent = new Intent(v.getContext(),RecordInterviewActivity.class);

		//put the interview id into the extras part of the intent
		myintent.putExtra(Util.ID_KEY,currentInterviewID);

		// Don't want to save the interview after stopping
		shouldSaveOnStop = false;
		
		//start the RecordInterviewActivity
		startActivityForResult(myintent,0);
	}


	/**
	 * Callback method for the input interview data button.
	 * Creates a new interview if none exists and passes the 
	 * interview id to the InputInterviewDataActivity.
	 * This activity will let the user input specific data about the 
	 * interview (date, interview subject, notes).
	 * @param v parameter required by onButtonPressed
	 */
	public void inputInterviewData(View v) {

		//Create the intent to switch to the data input activity
		Intent myintent = new Intent(v.getContext(),InputInterviewDataActivity.class);

		//put the interview id into the extras part of the intent
		myintent.putExtra(Util.ID_KEY,currentInterviewID);

		// Don't want to save the interview after stopping
		shouldSaveOnStop = false;
		
		//start the InputInterviewDataActivity
		startActivityForResult(myintent,0);
	}

}
